package com.googlecode.aleverr.yafotkiclient.api;

import android.util.Log;
import org.w3c.dom.Document;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class Utils {

    private static final String TAG = "Utils";

    private static final DocumentBuilder DOCUMENT_BUILDER;

    static {
        DocumentBuilder builder = null;
        try {
            builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            Log.e(TAG, e.getMessage(), e);
        } finally {
            DOCUMENT_BUILDER = builder;
        }
    }

    public static Document obtainDocument(String address, String accessToken, FormDataGenerator generator) {
        if (address == null || "".equals(address)) {
            return null;
        }
        HttpURLConnection connection = null;
        try {
            URL url = new URL(address);
            connection = (HttpURLConnection) url.openConnection();
            if (generator != null) {
                connection.setDoOutput(true);
                connection.setRequestMethod("POST");
                connection.setRequestProperty("Content-Type", "multipart/form-data;  boundary=" + FormDataGenerator.BOUNDARY);
            } else {
                connection.setRequestMethod("GET");
            }
            connection.setRequestProperty("Connection", "close");
            connection.setInstanceFollowRedirects(true);
            if (accessToken != null && !"".equals(accessToken)) {
                connection.setRequestProperty("Authorization", "OAuth " + accessToken);
            }
            if (generator != null) {
                OutputStream out = connection.getOutputStream();
                generator.write(out);
                out.close();
            } else {
                connection.connect();
            }
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED) {
                return DOCUMENT_BUILDER.parse(connection.getInputStream());
            }
        } catch (Exception e) {
            Log.e(TAG, e.getMessage(), e);
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
        return null;
    }

    public static Document obtainDocument(String address, String accessToken) {
        return obtainDocument(address, accessToken, null);
    }
}
